package org.sfgeeq.framework.helper;

import org.sfgeeq.framework.annotation.Inject;
import org.sfgeeq.framework.util.ArrayUtil;
import org.sfgeeq.framework.util.CollectionUtil;
import org.sfgeeq.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * IOC依赖注入助手类
 * Created by vmuser010 on 2016/8/26.
 */
public final class IocHelper {
    static {
        //获取所有的bean 类和Bean实例之间的映射关系 (Bean Map)
        Map<Class<?>,Object> beanMap=BeanHelper.getBeanMap();
        if(CollectionUtil.isNotEmpty(beanMap)){//判断 Map 是否非空
            //遍历 bean Map
            for(Map.Entry<Class<?>,Object> beanEntry:beanMap.entrySet()){
                //从BeanMap中获取bean类与bean实例
                Class<?> beanClass=beanEntry.getKey();
                Object beanValue=beanEntry.getValue();
                //获取Bean类定义的所有成员变量(简称BEAN FIELD)
                Field[] beanFilelds=beanClass.getDeclaredFields();
                if(ArrayUtil.isNotEmpty(beanFilelds)){
                    for(Field beanField:beanFilelds){
                        //判断当前bean field 是否带Inject注解
                        if(beanField.isAnnotationPresent(Inject.class)){
                            //在Bean Map中获取bean field对应的实例
                            Class<?> beanFieldClass=beanField.getType();
                            Object beanFieldInstance=beanMap.get(beanFieldClass);
                            if(beanValue!=null){
                                ReflectionUtil.setField(beanValue,beanField,beanFieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }
}
//entrySet 是键-值对的集合，set里面类型是MAP.Entry
//Map map=new HashMap();
//Iterator it=map.entrySet().iterator();
//Object key;
//Object value;
//while(it.hasNext()){
//        Map.Entry entry = (Map.Entry)it.next();
//        key=entry.getKey();
//        value=entry.getValue();
//        System.out.println(key+"="+value);
//        }